#!/usr/bin/env python
#coding:utf-8
from min_p import *
try:
    reload(sys)
    sys.setdefaultencoding("utf-8")
except:pass
from selenium import webdriver  
from selenium.webdriver.common.keys import Keys
from selenium.common import exceptions



class TAOBAO_LOGIN():
    

    def __init__(self):
        self.delay_wait = 10
        self.__login_url = "https://i.taobao.com/my_taobao.htm"
        #引入chromedriver.exe
        p_msg("open_firefox")
        self.driver = webdriver.Firefox()
        self.driver.set_window_size(1280,800)
        self.driver.set_page_load_timeout(self.delay_wait)  # 设定页面加载限制时间
        self.driver.implicitly_wait(10)
    def close(self):
        p_msg("close_firefox")
        self.driver.quit()
    def __del__(self):
        self.close()

    #检查元素是否存在
    def isElementExist(self,element):
        try:
            self.driver.find_element_by_xpath(element)
            return True
        except:return False
        
    #登录模块,采用Firefox可以自动获取千牛登录状态来直接登录（需要保持千牛登录）
    def login(self):
        p_msg("login_start")
        try:
            try:
                self.driver.get(self.__login_url)
            except exceptions.TimeoutException:  # 当页面加载时间超过设定时间，JS来停止加载
                self.driver.execute_script('window.stop()')
            time.sleep(1)
            self.driver.find_element_by_id('J_SubmitQuick').click()
            time.sleep(3)
            if "https://i.taobao.com/my_taobao.htm" in self.driver.current_url[0:38]:
                p_msg("login_success")
                return True
            else:
                p_msg("login_faild")
                return False
        except Exception, e:
            print e
            return log_wrong()

    #检查登录状态
    def check_login_state(self):
        if "login.taobao" in self.driver.current_url[0:30]:
            p_msg("login_is_out")
            return False
        else:
            return True

    #保持系统登录状态，访问如下四个页面，中间间隔4分钟
    def hold_login(self):
        try:
            time.sleep(5)
            self.driver.get("https://trade.taobao.com/trade/itemlist/list_sold_items.htm")
            time.sleep(60)
            self.driver.get("https://wuliu.taobao.com/user/order_list_new.htm")
            time.sleep(60)
            self.driver.get("https://rate.taobao.com/myRate.htm")
            time.sleep(60)
            self.driver.get("https://wuliu.taobao.com/user/logis_tools.htm")
            time.sleep(60)
        except Exception, e:
            return log_wrong()


